package org.yscz.webSocket;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yscz.webSocket.service.WebSocketService;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: pe
 * @description: WebSocket实现类
 * @description:
 * @author: muqs
 * @create: 2021-08-24 14:32
 **/
@ServerEndpoint(value = "/ws/{screenType}")
@Component
@Slf4j
public class WebSocket {

    @Autowired
    public static WebSocketService webSocketService;

    //concurrent包的线程安全Map，用来存放每个客户端对应的MyWebSocket对象。
    public static Map<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    public Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("screenType") String screenType, Session session) {
        // 设置session超时时间，-1永不超时
      session.setMaxIdleTimeout(-1);
        this.session = session;   //加入set中
        webSocketMap.put(screenType, this);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("screenType") String screenType) {
        log.info("======== 客户端【{}】断开连接 ========", screenType);
        webSocketMap.remove(screenType); //从map中删除
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息,message:{}", message);

        if (StringUtils.isEmpty(message)) {
            log.info("消息为空,message:{}", message);
            return;
        }

        try {
            JSONObject msgObj = JSONObject.parseObject(message);
            webSocketService.processMessage(msgObj);
        } catch (Exception e) {
            log.error("处理消息异常,error:{}", e);
        }
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("发生错误时,error:{}", error);
    }

    /*
     * @Title: sendMessage
     * @Author : muqs
     * @Date: 2021/8/24 10:52
     * @Description : 发送消息
     * @param : message
     * @Return : void
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     *
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            JSONObject msgObj = new JSONObject();
            msgObj.put("type", "error");
            try {
                session.getBasicRemote().sendText(msgObj.toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            log.error("发送消息出错：{}", e.getMessage());
        }
    }

    /*
     * @Title: sendInfo
     * @Author : muqs
     * @Date: 2021/8/24 10:52
     * @Description : 群发自定义消息
     * @param : message
     * @Return : void
     */
    public static void sendInfo(String message) {

        try {
            for (String key : webSocketMap.keySet()) {
                try {
                    webSocketMap.get(key).sendMessage(message);
                } catch (IOException e) {
                    log.error("发送消息出错, key:{}error:{}", key, e);
                    continue;
                }
            }
        } catch (Exception e) {
            log.error("群发消息出错,error:{}", e);
        }
    }

    /**
     * @Description: 获取主屏Session连接
     * @return: Session
     * @Author: muqs
     * @Date: 2021/8/27
     */
    public static Session getMainSession() {
        if (webSocketMap.get("main") != null) {
            return webSocketMap.get("main").session;
        }
        return null;
    }

    /**
     * @Description: 获取副屏Session连接
     * @return: Session
     * @Author: muqs
     * @Date: 2021/8/27
     */
    public static Session getViceSession() {
        if (webSocketMap.get("vice") != null) {
            return webSocketMap.get("vice").session;
        }
        return null;
    }
}